package com.ruoyi.web.controller.project;

import java.util.List;
import java.util.Map;

import com.google.common.collect.Lists;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.ProjectFile;
import com.ruoyi.system.service.IProjectFileService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 项目文件Controller
 *
 * @author zhaonz
 * @date 2023-06-02
 */
@Controller
@RequestMapping("/project/file")
public class ProjectFileController extends BaseController {
    private String prefix = "project/file";

    private static final Logger log = LoggerFactory.getLogger(ProjectFileController.class);

    private static final String FILE_DELIMETER = ",";

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private IProjectFileService projectFileService;

    @RequiresPermissions("system:file:view")
    @GetMapping()
    public String file() {
        return prefix + "/file";
    }

    /**
     * 查询项目文件列表
     */
    @RequiresPermissions("system:file:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ProjectFile projectFile) {
        startPage();
        List<ProjectFile> list = projectFileService.list(projectFile);
        return getDataTable(list);
    }

    /**
     * 导出项目文件列表
     */
    @RequiresPermissions("system:file:export")
    @Log(title = "项目文件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ProjectFile projectFile) {
        List<ProjectFile> list = projectFileService.list(projectFile);
        ExcelUtil<ProjectFile> util = new ExcelUtil<ProjectFile>(ProjectFile.class);
        return util.exportExcel(list, "项目文件数据");
    }

    /**
     * 新增项目文件
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存项目文件
     */
    @RequiresPermissions("system:file:add")
    @Log(title = "项目文件", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ProjectFile projectFile) {
        return toAjax(projectFileService.save(projectFile));
    }

    /**
     * 新增批量保存项目文件
     */
    @RequiresPermissions("system:file:add")
    @Log(title = "项目文件", businessType = BusinessType.INSERT)
    @RequestMapping(value = "/batchAdd", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult batchSave(@RequestBody List<ProjectFile> projectFile) {
        return toAjax(projectFileService.batchSave(projectFile));
    }

    /**
     * 修改项目文件
     */
    @RequiresPermissions("system:file:edit")
    @GetMapping("/edit/{fileId}")
    public String edit(@PathVariable("fileId") Long fileId, ModelMap mmap) {
        ProjectFile projectFile = projectFileService.getById(fileId);
        mmap.put("projectFile", projectFile);
        return prefix + "/edit";
    }

    /**
     * 修改保存项目文件
     */
    @RequiresPermissions("system:file:edit")
    @Log(title = "项目文件", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ProjectFile projectFile) {
        return toAjax(projectFileService.updateById(projectFile));
    }

    /**
     * 删除项目文件
     */
    @RequiresPermissions("system:file:remove")
    @Log(title = "项目文件", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(projectFileService.removeByIds(ids));
    }

    /**
     * 文件表单提交
     *
     * @param param
     * @param files
     * @return
     * @throws Exception
     */
    @PostMapping("/uploads")
    @ResponseBody
    public AjaxResult uploadFiles(@RequestParam Map<String, Object> param, List<MultipartFile> files) throws Exception {
        try {

            List<ProjectFile> list = Lists.newArrayList();

            if (!CollectionUtils.isEmpty(files)) {
                // 上传文件路径
                String filePath = RuoYiConfig.getUploadPath();

                for (MultipartFile file : files) {
                    ProjectFile projectFile = new ProjectFile();
                    // 上传并返回新文件名称
                    String fileName = FileUploadUtils.upload(filePath, file);
                    projectFile.setProjectId(MapUtils.getLong(param, "projectId"));
                    projectFile.setScheduleId(MapUtils.getString(param,"scheduleId"));
                    projectFile.setFilePath(fileName);
                    projectFile.setFileName(file.getOriginalFilename());
                    list.add(projectFile);
                }
            }
            projectFileService.uploadFiles(param, list);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("data", list);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 下载请求
     *
     * @param fileId 文件id
     */
    @GetMapping("/download/{fileId}")
    public void fileDownload(@PathVariable("fileId") Long fileId, HttpServletResponse response, HttpServletRequest request) {
        try {
            ProjectFile projectFile = projectFileService.getById(fileId);
            if (!FileUtils.checkAllowDownload(projectFile.getFileName())) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", projectFile.getFileName()));
            }
            String realFileName = System.currentTimeMillis() + "_" + projectFile.getFileName().substring(projectFile.getFileName().indexOf("_") + 1);
            String filePath = RuoYiConfig.getUploadPath() + "/" + projectFile.getFilePath();

            log.info("文件名称:{}, 文件路径:{}", realFileName, filePath);
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }
}
